<script setup lang="ts">
const props = defineProps<{ url?: ApiUrl | null }>();

const isEdit = computed(() => (props.url ? true : false));
const title = computed(() => (isEdit.value ? "修改" : "添加"));
const frm = ref(
  props.url
    ? {
        ...props.url,
        expired: props.url.has_expired ? props.url.expired : "",
        password: "",
      }
    : {
        expired: "",
        origin: "",
        password: "",
        has_expired: false,
        has_password: false,
        id: "",
      }
);

const { msg } = useStatus();
const { $post, $put } = use$fetch();

const noChangedPassword = "-NO-CHANGED-";
const password = ref(isEdit.value ? noChangedPassword : "");
const expired = ref(frm.value.expired || "");

const emit = defineEmits(["ok", "cancel"]);

const resetFrm = () => {
  frm.value = {
    id: "",
    expired: "",
    origin: "",
    password: "",
    has_expired: false,
    has_password: false,
  };
};

const handleSubmit = async () => {
  let pwd = password.value;
  if (isEdit && frm.value.has_password === false && pwd === noChangedPassword) {
    pwd = "";
  }
  const sendData = {
    ...frm.value,
    password: pwd,
    expired: expired.value,
  };

  console.log(sendData);

  if (isEdit.value) {
    await $put<AffResp>(`/admin/url/${frm.value.id}`, { ...sendData }, (v) => {
      msg.value = "修改成功";
      resetFrm();
      emit("ok");
      return v;
    });
    return;
  }
  await $post<IdResp>("/admin/url", { ...sendData }, (v) => {
    msg.value = "添加成功";
    resetFrm();
    emit("ok");
    return v;
  });
};

watch(
  () => frm.value.password,
  (nv) => {
    password.value = nv;
    frm.value.has_password = nv ? true : false;
  },
  { deep: true }
);
watch(
  () => frm.value.expired,
  (nv) => {
    const v = nv || "";
    expired.value = v;
    frm.value.has_expired = v ? true : false;
  },
  { deep: true }
);
</script>

<template>
  <Dialog>
    <form
      autocomplete="off"
      class="flex flex-col gap-y-4 required"
      @submit.prevent="handleSubmit"
    >
      <div class="text-lg">{{ title }}短链接</div>

      <label class="flex justify-start items-center">
        <div class="shrink-0 min-w-24 text-end">源地址：</div>
        <div
          class="border rounded px-3 py-1.5 grow"
          :class="{ 'bg-gray-100': isEdit }"
        >
          <input
            class="bg-transparent block w-full outline-none"
            type="url"
            v-model="frm.origin"
            :readonly="isEdit"
            required
          />
        </div>
      </label>
      <label
        class="flex justify-start"
        :class="{
          'items-start': frm.has_password,
          'items-center': !frm.has_password,
        }"
      >
        <div class="shrink-0 min-w-24 text-end">密码：</div>
        <div class="flex flex-col justify-start items-start grow gap-y-2">
          <div class="grow cursor-pointer">
            <div
              v-if="frm.has_password"
              class="flex justify-start items-center gap-x-1 text-cyan-600"
              @click="
                () => {
                  frm.password = '';
                  frm.has_password = false;
                }
              "
            >
              <Icon name="uil:trash" />
              <span>清空密码</span>
            </div>
          </div>
          <div class="border rounded px-3 py-1.5 grow w-full">
            <input
              class="bg-transparent block w-full outline-none"
              type="text"
              v-model="frm.password"
              :placeholder="
                isEdit && frm.has_password && password === noChangedPassword
                  ? '留空不修改密码'
                  : ''
              "
            />
          </div>
        </div>
      </label>

      <label class="flex justify-start items-center">
        <div class="shrink-0 min-w-24 text-end">过期时间：</div>
        <div class="flex flex-col justify-start items-start grow gap-y-2">
          <div class="grow cursor-pointer">
            <div
              v-if="frm.has_expired"
              class="flex justify-start items-center gap-x-1 text-cyan-600"
              @click="frm.expired = ''"
            >
              <Icon name="uil:trash" />
              <span>清空过期时间</span>
            </div>
          </div>
          <div class="border rounded px-3 py-1.5 grow">
            <DatetimePick
              mode="datetime"
              v-model="frm.expired"
              class="bg-transparent block w-full outline-none"
            />
          </div>
        </div>
      </label>

      <div class="flex justify-end items-center gap-x-2">
        <button
          class="bg-cyan-700 text-white rounded border px-3 py-1.5"
          type="submit"
        >
          提交
        </button>
        <button
          class="bg-gray-300 rounded border px-3 py-1.5"
          type="button"
          @click="
            () => {
              resetFrm();
              emit('cancel');
            }
          "
        >
          取消
        </button>
      </div>
    </form>
  </Dialog>
</template>
